<?php

namespace app\api\controller;

use app\api\logic\MpMenu;
use app\common\model\AppConfig;
use EasyWeChat\Factory;
use Symfony\Component\HttpFoundation\Response;
use think\Log;

class Mp extends Base
{
    /**
     * /api/mp/enter/1000
     * @return Response|void
     */
    public function enter()
    {
        // 获取应用编号
        $appId = getAppId();

        // 读取公众号配置
        $mpConfig = app(AppConfig::class)->getByIdAndType($appId, 'mp');

        // 读取微信小程序配置
        $mcpConfig = app(AppConfig::class)->getByIdAndType($appId, 'wx_mcp');

        // 配置
        $config = [
            'app_id' => $mpConfig['app_id'],
            'secret' => $mpConfig['secret'],
            'token' => $mpConfig['token'],
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);

        // 校验开发者微信服务器
        try {
            $app->server->push(function ($message) use ($mcpConfig) {
                try {
                    $logic = new MpMenu();
                    $logic->setAppId($mcpConfig['appId']);
                    return $logic->handler($message);
                } catch (\Exception $exception) {
                    $content = '出现错误';
                    $content .= ',错误信息:' . $exception->getMessage();
                    $content .= ',错误文件:' . $exception->getFile();
                    $content .= ',错误行号:' . $exception->getLine();
                    return $content;
                }
            });
            $response = $app->server->serve();
            return $response->send();
        } catch (\Exception $exception) {
            Log::record($exception->getMessage(), \think\facade\Log::ERROR);
        }
    }
}